package com.dsteiner.widgets.client;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PropertyChangeCollection {

	private Map<String, List<PropertyChangeListener>> listenersMap = new HashMap<String, List<PropertyChangeListener>>();
	private List<PropertyChangeListener> listeners = new ArrayList<PropertyChangeListener>();
	
	private Object source;

	private IJsUtil jsUtil;
	
	public PropertyChangeCollection(Object source) {
		this.source = source;
	}
	
	public void registerPropertyChangeListener(String propertyName, PropertyChangeListener propertyChangeListener){
		List<PropertyChangeListener> list = listenersMap.get(propertyName);
		if(list == null){
			list = new ArrayList<PropertyChangeListener>();
			listenersMap.put(propertyName, list);
		}
		listeners.add(propertyChangeListener);
		list.add(propertyChangeListener);
	}
	public void removePropertyChangeListener(PropertyChangeListener propertyChangeListener){
		listeners.remove(propertyChangeListener);
		for (List<PropertyChangeListener> listeners : listenersMap.values()) {
			listeners.remove(propertyChangeListener);
		}
	}
	
	public void firePropertyChange(String propertyName, Object oldValue, Object newValue){
		firePropertyChange(new PropertyChangeEvent(source, propertyName, oldValue, newValue));
	}
	public void firePropertyChange(final PropertyChangeEvent evt){
    	Object oldValue = evt.getOldValue();
    	Object newValue = evt.getNewValue();
		if(ObjectUtil.equals(oldValue, newValue))
			return;

		final List<PropertyChangeListener> list = listenersMap.get(evt.getPropertyName());
    	if (list == null || list.isEmpty())
    		return;

    	List<PropertyChangeListener> propertyChangeListeners = new ArrayList<PropertyChangeListener>();
    	propertyChangeListeners.addAll(list);
    	
    	for (PropertyChangeListener propertyChangeListener : propertyChangeListeners) {
    		propertyChangeListener.propertyChange(evt);
		}
	}

	private IJsUtil getJsUtil() {
		if(jsUtil == null)
			jsUtil = JsUtil.getInstance();
		return jsUtil;
	}

	public void registerJsUtil(IJsUtil jsUtil) {
		this.jsUtil = jsUtil;
	}
	
	public List<PropertyChangeListener> getPropertyChangeListeners() {
		return listeners;
	}
	
}
